import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

typedef LoadFeedbackCallback = void Function(
    BuildContext context,
    LoadMode loadState,
    double pulledExtent,
    double loadTriggerPullDistance,
    double loadIndicatorExtent,
    AxisDirection axisDirection,
    bool float,
    Duration completeDuration,
    bool enableInfiniteLoad,
    bool success,
    bool noMore);

class RefreshFooter {
  /// Key
  final Key key;

  /// 方位
  final AlignmentGeometry alignment;

  /// 提示加载文字
  final String loadText;

  /// 准备加载文字
  final String loadReadyText;

  /// 正在加载文字
  final String loadingText;

  /// 加载完成文字
  final String loadedText;

  /// 加载失败文字
  final String loadFailedText;

  /// 没有更多文字
  final String noMoreText;

  /// 显示额外信息(默认为时间)
  final bool showInfo;

  /// 更多信息
  final String infoText;

  /// 背景颜色
  final Color bgColor;

  /// 字体颜色
  final Color textColor;

  /// 更多信息文字颜色
  final Color infoColor;

  /// 失败图标
  final IconData failImage;

  /// 完成图标
  final IconData doneImage;

  /// 没有更多图标
  final IconData noMoreImage;

  /// 方向箭头图标
  final IconData arrowImage;

  /// 将加载动作传递给外部自定义布局
  final LoadFeedbackCallback feedbackCallback;

  RefreshFooter({
    this.key,
    this.alignment,
    this.loadText,
    this.loadReadyText,
    this.loadingText,
    this.loadedText,
    this.loadFailedText,
    this.noMoreText,
    this.showInfo: true,
    this.infoText,
    this.bgColor: Colors.transparent,
    textColor, //Colors.black,// 54 176 254
    this.infoColor: Colors.teal,
    this.feedbackCallback,
    this.failImage,
    this.doneImage,
    this.noMoreImage,
    this.arrowImage,
  }) : textColor = Color.fromRGBO(54, 176, 254, 1.0);

  /// 输出 Footer 子类
  CustomFooter realFooter;

  Footer getRealFooter() {
    LoadControlBuilder customFooterBuilder = (BuildContext context,
        LoadMode loadState,
        double pulledExtent,
        double loadTriggerPullDistance,
        double loadIndicatorExtent,
        AxisDirection axisDirection,
        bool float,
        Duration completeDuration,
        bool enableInfiniteLoad,
        bool success,
        bool noMore) {
      /// 在此处可将动作抛出给外部监听使用
      if (feedbackCallback != null) {
        feedbackCallback(
            context,
            loadState,
            pulledExtent,
            loadTriggerPullDistance,
            loadIndicatorExtent,
            axisDirection,
            float,
            completeDuration,
            enableInfiniteLoad,
            success,
            noMore);
        return SizedBox();
      }

      return ClassicalFooterWidget(
          key: key,
          refreshFooter: this,
          loadState: loadState,
          pulledExtent: pulledExtent,
          loadTriggerPullDistance: loadTriggerPullDistance,
          loadIndicatorExtent: loadIndicatorExtent,
          axisDirection: axisDirection,
          float: float,
          completeDuration: completeDuration,
          enableInfiniteLoad: enableInfiniteLoad,
          success: success,
          noMore: noMore);
    };

    /// 可在此设置 super 的默认属性值
    realFooter = CustomFooter(footerBuilder: customFooterBuilder);
    return realFooter;
  }
}

/// 自定义 Footer 组件
class ClassicalFooterWidget extends StatefulWidget {
  final RefreshFooter refreshFooter;
  final LoadMode loadState;
  final double pulledExtent;
  final double loadTriggerPullDistance;
  final double loadIndicatorExtent;
  final AxisDirection axisDirection;
  final bool float;
  final Duration completeDuration;
  final bool enableInfiniteLoad;
  final bool success;
  final bool noMore;

  ClassicalFooterWidget(
      {Key key,
      this.loadState,
      this.refreshFooter,
      this.pulledExtent,
      this.loadTriggerPullDistance,
      this.loadIndicatorExtent,
      this.axisDirection,
      this.float,
      this.completeDuration,
      this.enableInfiniteLoad,
      this.success,
      this.noMore})
      : super(key: key);

  @override
  ClassicalFooterWidgetState createState() => ClassicalFooterWidgetState();
}

class ClassicalFooterWidgetState extends State<ClassicalFooterWidget>
    with TickerProviderStateMixin<ClassicalFooterWidget> {
  // 是否到达触发加载距离
  bool _overTriggerDistance = false;
  bool get overTriggerDistance => _overTriggerDistance;
  set overTriggerDistance(bool over) {
    if (_overTriggerDistance != over) {
      _overTriggerDistance
          ? _readyController.forward()
          : _restoreController.forward();
    }
    _overTriggerDistance = over;
  }

  /// 默认语言
  GlobalEasyRefreshLocalizations _localizations =
      GlobalEasyRefreshLocalizations();

  /// 文本
  String get _loadText {
    return widget.refreshFooter.loadText ??
        (GlobalEasyRefreshLocalizations.of(context) == null
            ? _localizations.pushToLoad
            : GlobalEasyRefreshLocalizations.of(context).pushToLoad);
  }

  String get _loadReadyText {
    return widget.refreshFooter.loadReadyText ??
        (GlobalEasyRefreshLocalizations.of(context) == null
            ? _localizations.releaseToLoad
            : GlobalEasyRefreshLocalizations.of(context).releaseToLoad);
  }

  String get _loadingText {
    return widget.refreshFooter.loadingText ??
        (GlobalEasyRefreshLocalizations.of(context) == null
            ? _localizations.loading
            : GlobalEasyRefreshLocalizations.of(context).loading);
  }

  String get _loadedText {
    return widget.refreshFooter.loadedText ??
        (GlobalEasyRefreshLocalizations.of(context) == null
            ? _localizations.loaded
            : GlobalEasyRefreshLocalizations.of(context).loaded);
  }

  String get _loadFailedText {
    return widget.refreshFooter.loadFailedText ??
        (GlobalEasyRefreshLocalizations.of(context) == null
            ? _localizations.loadFailed
            : GlobalEasyRefreshLocalizations.of(context).loadFailed);
  }

  /// 没有更多文字
  String get _noMoreText {
    return widget.refreshFooter.noMoreText ??
        (GlobalEasyRefreshLocalizations.of(context) == null
            ? _localizations.noMore
            : GlobalEasyRefreshLocalizations.of(context).noMore);
  }

  String get _infoText {
    return widget.refreshFooter.infoText ??
        (GlobalEasyRefreshLocalizations.of(context) == null
            ? _localizations.updateAt
            : GlobalEasyRefreshLocalizations.of(context).updateAt);
  }

  // 动画
  AnimationController _readyController;
  Animation<double> _readyAnimation;
  AnimationController _restoreController;
  Animation<double> _restoreAnimation;

  // Icon旋转度
  double _iconRotationValue = 1.0;

  // 显示文字
  String get _showText {
    if (widget.noMore) return _noMoreText;
    if (widget.enableInfiniteLoad) {
      if (widget.loadState == LoadMode.loaded ||
          widget.loadState == LoadMode.inactive ||
          widget.loadState == LoadMode.drag) {
        return _finishedText;
      } else {
        return _loadingText;
      }
    }
    switch (widget.loadState) {
      case LoadMode.load:
        return _loadingText;
      case LoadMode.armed:
        return _loadingText;
      case LoadMode.loaded:
        return _finishedText;
      case LoadMode.done:
        return _finishedText;
      default:
        if (overTriggerDistance) {
          return _loadReadyText;
        } else {
          return _loadText;
        }
    }
  }

  // 加载结束文字
  String get _finishedText {
    if (!widget.success) return _loadFailedText;
    if (widget.noMore) return _noMoreText;
    return _loadedText;
  }

  // 加载结束图标
  IconData get _finishedIcon {
    if (!widget.success)
      return widget.refreshFooter.failImage ?? Icons.error_outline;
    if (widget.noMore)
      return widget.refreshFooter.noMoreImage ?? Icons.hourglass_empty;
    return widget.refreshFooter.doneImage ?? Icons.done;
  }

  // 更新时间
  DateTime _dateTime;
  // 获取更多信息
  String get _infoTextStr {
    if (widget.loadState == LoadMode.loaded) {
      _dateTime = DateTime.now();
    }
    String fillChar = _dateTime.minute < 10 ? "0" : "";
    return _infoText.replaceAll(
        "%T", "${_dateTime.hour}:$fillChar${_dateTime.minute}");
  }

  @override
  void initState() {
    super.initState();
    // 初始化时间
    _dateTime = DateTime.now();
    // 初始化动画
    _readyController = new AnimationController(
        duration: const Duration(milliseconds: 200), vsync: this);
    _readyAnimation = new Tween(begin: 0.5, end: 1.0).animate(_readyController)
      ..addListener(() {
        setState(() {
          if (_readyAnimation.status != AnimationStatus.dismissed) {
            _iconRotationValue = _readyAnimation.value;
          }
        });
      });
    _readyAnimation.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        _readyController.reset();
      }
    });
    _restoreController = new AnimationController(
        duration: const Duration(milliseconds: 200), vsync: this);
    _restoreAnimation =
        new Tween(begin: 1.0, end: 0.5).animate(_restoreController)
          ..addListener(() {
            setState(() {
              if (_restoreAnimation.status != AnimationStatus.dismissed) {
                _iconRotationValue = _restoreAnimation.value;
              }
            });
          });
    _restoreAnimation.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        _restoreController.reset();
      }
    });
  }

  @override
  void dispose() {
    _readyController.dispose();
    _restoreController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // 是否反向
    bool isReverse = widget.axisDirection == AxisDirection.up ||
        widget.axisDirection == AxisDirection.left;
    // 是否到达触发加载距离
    overTriggerDistance = widget.loadState != LoadMode.inactive &&
        widget.pulledExtent >= widget.loadTriggerPullDistance;
    return Stack(
      children: <Widget>[
        Positioned(
          top: !isReverse ? 0.0 : null,
          bottom: isReverse ? 0.0 : null,
          left: 0.0,
          right: 0.0,
          child: Container(
            alignment: widget.refreshFooter.alignment ?? !isReverse
                ? Alignment.topCenter
                : Alignment.bottomCenter,
            width: double.infinity,
            height: widget.loadIndicatorExtent > widget.pulledExtent
                ? widget.loadIndicatorExtent
                : widget.pulledExtent,
            color: widget.refreshFooter.bgColor,
            child: SizedBox(
                height: widget.loadIndicatorExtent,
                width: double.infinity,
                // child: Row(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: _buildContent(isReverse),
                )),
          ),
        ),
      ],
    );
  }

  // 构建显示内容
  List<Widget> _buildContent(bool isReverse) {
    if (widget.noMore) {
      return <Widget>[_noMoreBottomLineWidget()];
    }
    return <Widget>[
      // Expanded(
      //   flex: 2,
      //   child:
      Container(
          // alignment: Alignment.centerRight,
          alignment: Alignment.center,
          // padding: EdgeInsets.only(
          //   right: 10.0,
          // ),
          child:
              // (widget.loadState == LoadMode.load ||
              //             widget.loadState == LoadMode.armed) &&
              //         !widget.noMore
              //     ?
              Container(
            width: 20.0,
            height: 20.0,
            child: CircularProgressIndicator(
              strokeWidth: 2.0,
              valueColor: AlwaysStoppedAnimation(
                widget.refreshFooter.textColor,
              ),
            ),
          )
          // :
          // widget.loadState == LoadMode.loaded ||
          //         widget.loadState == LoadMode.done ||
          //         (widget.enableInfiniteLoad &&
          //             widget.loadState != LoadMode.loaded) ||
          //         widget.noMore
          //     ? Icon(
          //         _finishedIcon,
          //         color: widget.refreshFooter.textColor,
          //       )
          //     : Transform.rotate(
          //         child: Icon(
          //           !isReverse
          //               ? (widget.refreshFooter.arrowImage ??
          //                   Icons.arrow_upward)
          //               : (widget.refreshFooter.arrowImage ??
          //                   Icons.arrow_downward),
          //           color: widget.refreshFooter.textColor,
          //         ),
          //         angle: 2 * pi * _iconRotationValue,
          //       ),
          ),
      // ),
      // Expanded(
      //   flex: 3,
      //   child: Column(
      //     crossAxisAlignment: CrossAxisAlignment.center,
      //     mainAxisAlignment: MainAxisAlignment.center,
      //     children: <Widget>[
      //       Text(
      //         _showText,
      //         style: TextStyle(
      //           fontSize: 16.0,
      //           color: widget.refreshFooter.textColor,
      //         ),
      //       ),
      //       widget.refreshFooter.showInfo
      //           ? Container(
      //               margin: EdgeInsets.only(
      //                 top: 2.0,
      //               ),
      //               child: Text(
      //                 _infoTextStr,
      //                 style: TextStyle(
      //                   fontSize: 12.0,
      //                   color: widget.refreshFooter.infoColor,
      //                 ),
      //               ),
      //             )
      //           : Container(),
      //     ],
      //   ),
      // ),
      // Expanded(
      //   flex: 2,
      //   child: SizedBox(),
      // ),
    ];
  }

  /// 没有更多数据时，显示我是有底线的footer
  Widget _noMoreBottomLineWidget() {
    return Container(
      child: Row(
        children: <Widget>[
          Expanded(
            child: Divider(),
            flex: 2,
          ),
          // Spacer(flex: 2,),
          Text(
            'Bottom Line',
            style: TextStyle(fontSize: 14.0, color: Color(0xFF999999)),
          ),
          // Spacer(flex: 2,),
          Expanded(
            child: Divider(),
            flex: 2,
          )
        ],
      ),
    );
  }
}
